// 常量
const PENDDING = 'pendding';
const RESOLVED = 'resolved';
const REJECTED = 'rejected';

// 构造函数
function MiniPromise(cb) {
    const that = this;

    that.status = PENDDING;
    that.value = null;
    that.error = null;

    // 保存成功后，要执行的回调函数
    that.resolvedCallback = [];
    that.rejectCallback = [];

    /**
     * 成功处理
     * @param {*} value
     */
    function resolve(value) {
        if (that.status === PENDDING) {
            that.status = RESOLVED;
            that.value = value;
            that.resolvedCallback.map((callback) => callback(that.value));
        }
    }

    /**
     * 失败处理
     * @param {*} error
     */
    function reject(error) {
        if (that.status === PENDDING) {
            that.status = REJECTED;
            that.error = error;
            that.rejectCallback.map((callback) => callback(that.error));
        }
    }

    // 创建这个 Promise 对象时，就会立即执行这个 promise 内部的逻辑
    cb(resolve, reject);
    // try {

    // } catch (error) {
    //     reject(error);
    // }
}

/**
 * 添加原型方法
 * @param {*} onResolvedCallback
 * @param {*} onRejectedCallback
 */
MiniPromise.prototype.then = function (onResolvedCallback, onRejectedCallback) {
    this.resolvedCallback.push(onResolvedCallback);
    this.rejectCallback.push(onRejectedCallback);
};

const promise = new MiniPromise((resolve, reject) => {
    // throw 123;
    resolve('ok');
    // setTimeout(() => {
    // resolve('ok');
    // reject(123);
    // throw 123;
    // reject('error');
    // }, 0);
});

promise.then(
    (res) => {
        console.log('res', res);
    },
    (err) => {
        console.log('err', err);
    }
);
